package com.roc.base.mall.configuration.db;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = MainDataSourceConfigurer.PACKAGE, sqlSessionFactoryRef = "mainSqlSessionFactory", sqlSessionTemplateRef = "mainSqlSessionTemplate")
public class MainDataSourceConfigurer {

    static final String PACKAGE = "com.roc.base.mall.dao.main";

    /**
     * SqlSessionFactory
     * @return
     * @throws Exception
     */
    @Primary
    @Bean(name = "mainSqlSessionFactory")
    public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDealerDataSource") DataSource mainDataSource) throws Exception{
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/main/*.xml"));
        sessionFactory.setDataSource(mainDataSource);
        sessionFactory.setPlugins(new Interceptor[]{new PageInterceptor()});
        return sessionFactory.getObject();
    }


    @Bean(name = "mainSqlSessionTemplate")
    public SqlSessionTemplate erpSqlSessionTemplate(
            @Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }



}
